package com.secsbrain.development.dal.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author yjy
 * @date 2019/12/26 9:58
 **/
public class RibbonResolveMapConfig {

    private static final Logger log = LoggerFactory.getLogger(RibbonResolveMapConfig.class);

    /** 直连配置文件地址, 优先级高于spring配置 */
    @Value("${ribbon.resolve.file:}")
    public String resolveFile;
    /** 开启直连模式 */
    private boolean enabled = true;
    /** 是否打印直连信息 */
    private boolean logChooseServer = false;
    private Map<String, String> servers = new HashMap<>();

    @PostConstruct
    public void init() {
        this.servers.forEach((k, v) -> {
            log.info("Ribbon rule from config > resolve service [{}] to address [{}]", k, v);
        });
        if (resolveFile != null && !"".equals(resolveFile)) {
            Properties properties = new Properties();
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(new File(resolveFile));
                properties.load(fis);
            } catch (IOException e) {
                throw new IllegalStateException("Unload " + resolveFile + ", cause: " + e.getMessage(), e);
            } finally {
                try {
                    if (null != fis) {
                        fis.close();
                    }
                } catch (IOException e) {
                    // ignore
                }
            }
            Enumeration names = properties.propertyNames();
            while (names.hasMoreElements()) {
                String serviceName = (String) names.nextElement();
                String address = properties.getProperty(serviceName);
                this.servers.put(serviceName, address);
                log.info("Ribbon rule from ribbon.resolve.file > resolve service [{}] to address [{}]", serviceName, address);
            }
        }
    }

    public Map<String, String> getServers() {
        return servers;
    }

    public boolean isLogChooseServer() {
        return logChooseServer;
    }

    public void setLogChooseServer(boolean logChooseServer) {
        this.logChooseServer = logChooseServer;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public void setServers(Map<String, String> servers) {
        this.servers = servers;
    }
}
